﻿using DevExpress.XtraBars;
using DevExpress.XtraBars.Docking;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ImagePro
{
    public partial class FrmMain : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        public FrmMain()
        {
            InitializeComponent();
            ShowObjectBrowser();
            documentManager.DocumentActivate += (s, e) =>
            {
                currentDocForm = (XtraForm)(e.Document?.Control);
                UpdateEnable();
            };
            UpdateEnable();
            InitFilterColor();
        }

        private void InitFilterColor()
        {
            Dictionary<string, Dictionary<string, int[]>> filters = new Dictionary<string, Dictionary<string, int[]>>();
            Dictionary<string, int[]> temp = new Dictionary<string, int[]>();
            temp.Add("默认", new int[] { 0xe74c3c, 0xe67e22, 0xf1c40f, 0x1abc9c, 0x2ecc71, 0x3498db, 0x9b59b6, 0x34495e, 0x95a5a6, 0xecf0f1 });
            temp.Add("中国", new int[] { 0xff4757, 0xff6348, 0xff6b81, 0xffa502, 0xff7f50, 0xeccc68, 0x7bed9f, 0x2ed573, 0x70a1ff, 0x1e90ff, 0x5352ed, 0x3742fa, 0x747d8c, 0x747d8c });
            filters.Add("Flat", temp);

            temp = new Dictionary<string, int[]>();
            temp.Add("中性", new int[] { 0xf5f5f5, 0xf0f0f0, 0xd9d9d9, 0xbfbfbf, 0x8c8c8c, 0x595959, 0x434343, 0x262626, 0x1f1f1f, 0x141414 });
            temp.Add("薄暮", new int[] { 0xfff1f0, 0xffccc7, 0xffa39e, 0xff7875, 0xff4d4f, 0xf5222d, 0xcf1322, 0xa8071a, 0x820014, 0x5c0011 });
            temp.Add("火山", new int[] { 0xfff2e8, 0xffd8bf, 0xffbb96, 0xff9c6e, 0xff7a45, 0xfa541c, 0xd4380d, 0xad2102, 0x871400, 0x610b00 });
            temp.Add("日暮", new int[] { 0xfff7e6, 0xffe7ba, 0xffd591, 0xffc069, 0xffa940, 0xfa8c16, 0xd46b08, 0xad4e00, 0x873800, 0x612500 });
            temp.Add("金盏花", new int[] { 0xfffbe6, 0xfff1b8, 0xffe58f, 0xffd666, 0xffc53d, 0xfaad14, 0xd48806, 0xad6800, 0x874d00, 0x613400 });
            temp.Add("日出", new int[] { 0xfeffe6, 0xffffb8, 0xfffb8f, 0xfff566, 0xffec3d, 0xfadb14, 0xd4b106, 0xad8b00, 0x876800, 0x614700 });
            temp.Add("青柠", new int[] { 0xfcffe6, 0xf4ffb8, 0xeaff8f, 0xd3f261, 0xbae637, 0xa0d911, 0x7cb305, 0x5b8c00, 0x3f6600, 0x254000 });
            temp.Add("极光绿", new int[] { 0xf6ffed, 0xd9f7be, 0xb7eb8f, 0x95de64, 0x73d13d, 0x52c41a, 0x389e0d, 0x237804, 0x135200, 0x092b00 });
            temp.Add("明清", new int[] { 0xe6fffb, 0xb5f5ec, 0x87e8de, 0x5cdbd3, 0x36cfc9, 0x13c2c2, 0x08979c, 0x006d75, 0x00474f, 0x002329 });
            temp.Add("拂晓蓝", new int[] { 0xe6f7ff, 0xbae7ff, 0x91d5ff, 0x69c0ff, 0x40a9ff, 0x1890ff, 0x096dd9, 0x0050b3, 0x003a8c, 0x002766 });
            temp.Add("极客蓝", new int[] { 0xf0f5ff, 0xd6e4ff, 0xadc6ff, 0x85a5ff, 0x597ef7, 0x2f54eb, 0x1d39c4, 0x10239e, 0x061178, 0x030852 });
            temp.Add("酱紫", new int[] { 0xf9f0ff, 0xefdbff, 0xd3adf7, 0xb37feb, 0x9254de, 0x722ed1, 0x531dab, 0x391085, 0x22075e, 0x120338 });
            temp.Add("法式洋红", new int[] { 0xfff0f6, 0xffd6e7, 0xffadd2, 0xff85c0, 0xf759ab, 0xeb2f96, 0xc41d7f, 0x9e1068, 0x780650, 0x520339 });
            filters.Add("Ant Design", temp);

            temp = new Dictionary<string, int[]>();
            temp.Add("Gray", new int[] { 0xf8f9fa, 0xf1f3f5, 0xe9ecef, 0xdee2e6, 0xced4da, 0xadb5bd, 0x868e96, 0x495057, 0x343a40, 0x212529 });
            temp.Add("Red", new int[] { 0xfff5f5, 0xffe3e3, 0xffc9c9, 0xffa8a8, 0xff8787, 0xff6b6b, 0xfa5252, 0xf03e3e, 0xe03131, 0xc92a2a });
            temp.Add("Pink", new int[] { 0xfff0f6, 0xffdeeb, 0xfcc2d7, 0xfaa2c1, 0xf783ac, 0xf06595, 0xe64980, 0xd6336c, 0xc2255c, 0xa61e4d });
            temp.Add("Grape", new int[] { 0xf8f0fc, 0xf3d9fa, 0xeebefa, 0xe599f7, 0xda77f2, 0xcc5de8, 0xbe4bdb, 0xae3ec9, 0x9c36b5, 0x862e9c });
            temp.Add("Violet", new int[] { 0xf3f0ff, 0xe5dbff, 0xd0bfff, 0xb197fc, 0x9775fa, 0x845ef7, 0x7950f2, 0x7048e8, 0x6741d9, 0x5f3dc4 });
            temp.Add("Indigo", new int[] { 0xedf2ff, 0xdbe4ff, 0xbac8ff, 0x91a7ff, 0x748ffc, 0x5c7cfa, 0x4c6ef5, 0x4263eb, 0x3b5bdb, 0x364fc7 });
            temp.Add("Blue", new int[] { 0xe7f5ff, 0xd0ebff, 0xa5d8ff, 0x74c0fc, 0x4dabf7, 0x339af0, 0x228be6, 0x1c7ed6, 0x1971c2, 0x1864ab });
            temp.Add("Cyan", new int[] { 0xe3fafc, 0xc5f6fa, 0x99e9f2, 0x66d9e8, 0x3bc9db, 0x22b8cf, 0x15aabf, 0x1098ad, 0x0c8599, 0x0b7285 });
            temp.Add("Teal", new int[] { 0xe6fcf5, 0xc3fae8, 0x96f2d7, 0x63e6be, 0x38d9a9, 0x20c997, 0x12b886, 0x0ca678, 0x099268, 0x087f5b });
            temp.Add("Green", new int[] { 0xebfbee, 0xd3f9d8, 0xb2f2bb, 0x8ce99a, 0x69db7c, 0x51cf66, 0x40c057, 0x37b24d, 0x2f9e44, 0x2b8a3e });
            temp.Add("Lime", new int[] { 0xf4fce3, 0xe9fac8, 0xd8f5a2, 0xc0eb75, 0xa9e34b, 0x94d82d, 0x82c91e, 0x74b816, 0x66a80f, 0x5c940d });
            temp.Add("Yellow", new int[] { 0xfff9db, 0xfff3bf, 0xffec99, 0xffe066, 0xffd43b, 0xfcc419, 0xfab005, 0xf59f00, 0xf08c00, 0xe67700 });
            temp.Add("Orange", new int[] { 0xfff4e6, 0xffe8cc, 0xffd8a8, 0xffc078, 0xffa94d, 0xff922b, 0xfd7e14, 0xf76707, 0xe8590c, 0xd9480f });
            filters.Add("Open Color", temp);

            temp = new Dictionary<string, int[]>();
            temp.Add("Red", new int[] { 0xffebee, 0xffcdd2, 0xef9a9a, 0xe57373, 0xef5350, 0xf44336, 0xe53935, 0xd32f2f, 0xc62828, 0xb71c1c });
            temp.Add("Pink", new int[] { 0xfce4ec, 0xf8bbd0, 0xf48fb1, 0xf06292, 0xec407a, 0xe91e63, 0xd81b60, 0xc2185b, 0xad1457, 0x880e4f });
            temp.Add("Purple", new int[] { 0xf3e5f5, 0xe1bee7, 0xce93d8, 0xba68c8, 0xab47bc, 0x9c27b0, 0x8e24aa, 0x7b1fa2, 0x6a1b9a, 0x4a148c });
            temp.Add("Deep Purple", new int[] { 0xede7f6, 0xd1c4e9, 0xb39ddb, 0x9575cd, 0x7e57c2, 0x673ab7, 0x5e35b1, 0x512da8, 0x4527a0, 0x311b92 });
            temp.Add("Indigo", new int[] { 0xe8eaf6, 0xc5cae9, 0x9fa8da, 0x7986cb, 0x5c6bc0, 0x3f51b5, 0x3949ab, 0x303f9f, 0x283593, 0x1a237e });
            temp.Add("Blue", new int[] { 0xe3f2fd, 0xbbdefb, 0x90caf9, 0x64b5f6, 0x42a5f5, 0x2196f3, 0x1e88e5, 0x1976d2, 0x1565c0, 0x0d47a1 });
            temp.Add("Light Blue", new int[] { 0xe1f5fe, 0xb3e5fc, 0x81d4fa, 0x4fc3f7, 0x29b6f6, 0x03a9f4, 0x039be5, 0x0288d1, 0x0277bd, 0x01579b });
            temp.Add("Cyan", new int[] { 0xe0f7fa, 0xb2ebf2, 0x80deea, 0x4dd0e1, 0x26c6da, 0x00bcd4, 0x00acc1, 0x0097a7, 0x00838f, 0x006064 });
            temp.Add("Teal", new int[] { 0xe0f2f1, 0xb2dfdb, 0x80cbc4, 0x4db6ac, 0x26a69a, 0x009688, 0x00897b, 0x00796b, 0x00695c, 0x004d40 });
            temp.Add("Green", new int[] { 0xe8f5e9, 0xc8e6c9, 0xa5d6a7, 0x81c784, 0x66bb6a, 0x4caf50, 0x43a047, 0x388e3c, 0x2e7d32, 0x1b5e20 });
            temp.Add("Light Green", new int[] { 0xf1f8e9, 0xdcedc8, 0xc5e1a5, 0xaed581, 0x9ccc65, 0x8bc34a, 0x7cb342, 0x689f38, 0x558b2f, 0x33691e });
            temp.Add("Lime", new int[] { 0xf9fbe7, 0xf0f4c3, 0xe6ee9c, 0xdce775, 0xd4e157, 0xcddc39, 0xc0ca33, 0xafb42b, 0x9e9d24, 0x827717 });
            temp.Add("Yellow", new int[] { 0xfffde7, 0xfff9c4, 0xfff59d, 0xfff176, 0xffee58, 0xffeb3b, 0xfdd835, 0xfbc02d, 0xf9a825, 0xf57f17 });
            temp.Add("Amber", new int[] { 0xfff8e1, 0xffecb3, 0xffe082, 0xffd54f, 0xffca28, 0xffc107, 0xffb300, 0xffa000, 0xff8f00, 0xff6f00 });
            temp.Add("Orange", new int[] { 0xfff3e0, 0xffe0b2, 0xffcc80, 0xffb74d, 0xffa726, 0xff9800, 0xfb8c00, 0xf57c00, 0xef6c00, 0xe65100 });
            temp.Add("Deep Orange", new int[] { 0xfbe9e7, 0xffccbc, 0xffab91, 0xff8a65, 0xff7043, 0xff5722, 0xf4511e, 0xe64a19, 0xd84315, 0xbf360c });
            temp.Add("Brown", new int[] { 0xefebe9, 0xd7ccc8, 0xbcaaa4, 0xa1887f, 0x8d6e63, 0x795548, 0x6d4c41, 0x5d4037, 0x4e342e, 0x3e2723 });
            temp.Add("Grey", new int[] { 0xfafafa, 0xf5f5f5, 0xeeeeee, 0xe0e0e0, 0xbdbdbd, 0x9e9e9e, 0x757575, 0x616161, 0x424242, 0x212121 });
            temp.Add("Blue Grey", new int[] { 0xeceff1, 0xcfd8dc, 0xb0bec5, 0x90a4ae, 0x78909c, 0x607d8b, 0x546e7a, 0x455a64, 0x37474f, 0x263238 });
            filters.Add("Material", temp);


            popupMenuFilter.ItemLinks.Clear();
            popupMenuFilter.AddItems(filters.Keys.ToList().Select(f =>
            {
                var btn = new BarButtonItem();
                btn.Caption = f;
                btn.ItemClick += (s, arg) =>
                {
                    ClickFilterItem(f, filters);
                };
                return btn;
            }).ToArray());
            ClickFilterItem("Flat", filters);
        }

        private void ClickFilterItem(string f, Dictionary<string, Dictionary<string, int[]>> filters)
        {
            barButtonItemFilter.Caption = f;
            ribbonGalleryBarItemFilter.Gallery.Groups.Clear();
            ribbonGalleryBarItemFilter.Gallery.Groups.AddRange(filters[f].Keys.ToList().Select(ff =>
            {
                var group = new GalleryItemGroup();
                group.Caption = ff;
                for (int i = 0; i < filters[f][ff].Length; i++)
                {
                    Color tColor = Color.FromArgb(filters[f][ff][i]);
                    Color nc = Color.FromArgb(tColor.R, tColor.G, tColor.B);
                    Bitmap img = new Bitmap(64, 36);
                    using (Graphics g = Graphics.FromImage(img))
                    {
                        g.Clear(nc);
                    }
                    var item = new GalleryItem(img, $"{ff}{i + 1}", "");
                    item.ImageOptions.Image = img;
                    item.ItemClick += (se, argu) => { Filtering(nc, "单色"); };
                    group.Items.Add(item);
                }
                return group;
            }).ToArray());
        }

        private void UpdateEnable()
        {
            if (currentDocForm is FrmImg)
            {
                ImageItem ii = ((FrmImg)currentDocForm).ImageItem;
                barStaticItem.Caption = $"尺寸：{ii.Image.Width}×{ii.Image.Height} | {ii.Name}";
                var repositoryItem = new DevExpress.XtraEditors.Repository.RepositoryItemSpinEdit();
                repositoryItem.MaxValue = (ii.Image.Width < ii.Image.Height ? ii.Image.Width : ii.Image.Height) / 5;
                barEditItemSkip.Edit = repositoryItem;
                ribbonPageGroupImg.Enabled = true;
                ribbonPageGroupFilter.Enabled = true;
                ribbonPageGroupExchange.Enabled = true;
                ribbonPageGroupClasses.Enabled = true;
                ribbonPageGroupPaint.Enabled = clusteringItems.Count > 0;
                barButtonItemSave.Enabled = true;
                barButtonItemCopyImg.Enabled = true;
                barButtonItemColoring.Enabled = clusteringItems.Count > 0;
            }
            else
            {
                barStaticItem.Caption = "就绪";
                ribbonPageGroupImg.Enabled = false;
                ribbonPageGroupFilter.Enabled = false;
                ribbonPageGroupExchange.Enabled = false;
                ribbonPageGroupClasses.Enabled = false;
                ribbonPageGroupPaint.Enabled = false;
                barButtonItemSave.Enabled = false;
                barButtonItemCopyImg.Enabled = false;
                barButtonItemColoring.Enabled = false;
            }

            if (currentDocForm is FrmImg || currentDocForm is FrmClasses)
            {
                barButtonItemRename.Enabled = true;
            }
            else
            {
                barButtonItemRename.Enabled = false;
            }

            barButtonItemDel.Enabled = currentDocForm != null;
        }

        XtraForm currentDocForm;
        List<XtraForm> xtraDocForms = new List<XtraForm>();
        List<ImageItem> imageItems = new List<ImageItem>();
        List<ClusteringItem> clusteringItems = new List<ClusteringItem>();
        DockPanel dockPanelObjectBrowser;
        ObjectBrowser objectBrowser;
        DockPanel dockPanelShadingOptions;
        ShadingOptions shadingOptions;
        DockPanel dockPanelResizeSettings;

        private void ShowResizeSettings()
        {
            if (dockPanelResizeSettings == null)
            {
                dockPanelResizeSettings = dockManager.AddPanel(DockingStyle.Right);
                dockPanelResizeSettings.Text = "尺寸调节";
                ResizeSettings resizeSettings = new ResizeSettings();
                dockPanelResizeSettings.Controls.Add(resizeSettings);
                resizeSettings.Dock = DockStyle.Fill;
                dockPanelResizeSettings.ClosedPanel += (s, arg) => { dockPanelResizeSettings = null; };
                resizeSettings.OnStart += () =>
                {
                    Resizeing(resizeSettings);
                };
            }
            else
            {
                dockPanelResizeSettings.Focus();
            }
        }

        private void ShowObjectBrowser()
        {
            if (dockPanelObjectBrowser == null)
            {
                dockPanelObjectBrowser = dockManager.AddPanel(DockingStyle.Left);
                dockPanelObjectBrowser.Text = "对象浏览器";
                objectBrowser = new ObjectBrowser(imageItems, clusteringItems);
                dockPanelObjectBrowser.Controls.Add(objectBrowser);
                objectBrowser.Dock = DockStyle.Fill;
                objectBrowser.UpdateObject();
                objectBrowser.OnImageItemLinkClick = imageItemClick;
                objectBrowser.OnClusterimgItemLinkClick = clusteringItemClick;
                dockPanelObjectBrowser.ClosedPanel += (s, arg) => { dockPanelObjectBrowser = null; };
            }
            else
            {
                dockPanelObjectBrowser.Focus();
            }
        }

        private void ShowShadingOptions(Dictionary<Color, Color> cc)
        {
            if (dockPanelShadingOptions == null)
            {
                dockPanelShadingOptions = dockManager.AddPanel(DockingStyle.Right);
                dockPanelShadingOptions.Width = 300;
                dockPanelShadingOptions.Text = "自定义着色";
                shadingOptions = new ShadingOptions(cc);
                dockPanelShadingOptions.Controls.Add(shadingOptions);
                shadingOptions.Dock = DockStyle.Fill;
                dockPanelObjectBrowser.ClosedPanel += (s, arg) => { dockPanelObjectBrowser = null; };
                shadingOptions.OnStart += Coloring;
            }
            else
            {
                dockPanelShadingOptions.Focus();
                shadingOptions.UpdateColors(cc);
            }
        }

        private void imageItemClick(ImageItem imageItem)
        {
            FrmImg frmImg = (FrmImg)xtraDocForms.FirstOrDefault(f => f is FrmImg && ((FrmImg)f).ImageItem == imageItem);
            if (frmImg == null)
            {
                XtraForm childForm = new FrmImg(imageItem);
                xtraDocForms.Add(childForm);
                childForm.MdiParent = this;
                childForm.Show();
                childForm.FormClosed += (s, e) => { xtraDocForms.Remove(childForm); };
            }
            else
            {
                frmImg.Focus();
            }
        }

        private void clusteringItemClick(ClusteringItem clusteringItem)
        {
            FrmClasses frmClasses = (FrmClasses)xtraDocForms.FirstOrDefault(f => f is FrmClasses && ((FrmClasses)f).ColorClustering == clusteringItem.ColorClustering);
            if (frmClasses == null)
            {
                XtraForm childForm = new FrmClasses(clusteringItem);
                xtraDocForms.Add(childForm);
                childForm.MdiParent = this;
                childForm.Show();
                childForm.FormClosed += (s, arg) => { xtraDocForms.Remove(childForm); };
            }
            else
            {
                frmClasses.Focus();
            }
        }


        private void FrmMain_Load(object sender, EventArgs e)
        {

        }

        private void barButtonItemObject_ItemClick(object sender, ItemClickEventArgs e)
        {
            ShowObjectBrowser();
        }

        #region 直方图
        private void barButtonItemHistogram_ItemClick(object sender, ItemClickEventArgs e)
        {
            splashScreenManager.ShowWaitForm();
            splashScreenManager.SetWaitFormDescription("正在统计，已完成0%");
            if (!(currentDocForm is FrmImg))
            {
                return;
            }
            FrmImgHistogram frmImgHistogram = (FrmImgHistogram)xtraDocForms.FirstOrDefault(f => f is FrmImgHistogram && ((FrmImgHistogram)f).ImageItem == ((FrmImg)currentDocForm).ImageItem);
            if (frmImgHistogram == null)
            {
                XtraForm childForm = new FrmImgHistogram(((FrmImg)currentDocForm).ImageItem, p =>
                {
                    splashScreenManager.SetWaitFormDescription($"正在统计，已完成{p}%");
                });
                xtraDocForms.Add(childForm);
                childForm.MdiParent = this;
                childForm.Show();
                childForm.FormClosed += (s, arg) => { xtraDocForms.Remove(childForm); };
            }
            else
            {
                frmImgHistogram.Focus();
            }
            splashScreenManager.CloseWaitForm();
        }
        #endregion

        #region 着色
        private void Coloring(Dictionary<Color, Color> colorss)
        {
            splashScreenManager.ShowWaitForm();
            if (!(currentDocForm is FrmImg))
            {
                return;
            }
            ImageItem sourceImageItem = ((FrmImg)currentDocForm).ImageItem;
            Image image = new ImageHelper((Bitmap)sourceImageItem.Image).GetMainColor(colorss, p =>
            {
                splashScreenManager.SetWaitFormDescription($"正在着色，已完成 {p}%");
            });
            ImageItem ii = new ImageItem(image, $"{Path.GetFileNameWithoutExtension(sourceImageItem.Name)}_着色{Path.GetExtension(sourceImageItem.Name)}");
            imageItems.Add(ii);
            if (objectBrowser != null)
            {
                objectBrowser.UpdateObject();
                objectBrowser.ToClickItemLink(ii);
            }
            else
            {
                imageItemClick(ii);
            }
            splashScreenManager.CloseWaitForm();
        }
        #endregion

        #region 滤镜
        private void Filtering(Color cc, string name)
        {
            splashScreenManager.ShowWaitForm();
            splashScreenManager.SetWaitFormDescription($"正在应用{name}滤镜");
            if (!(currentDocForm is FrmImg))
            {
                return;
            }
            ImageItem sourceImageItem = ((FrmImg)currentDocForm).ImageItem;
            Image image = new ImageHelper((Bitmap)sourceImageItem.Image).GetFilter(cc);
            ImageItem ii = new ImageItem(image, $"{Path.GetFileNameWithoutExtension(sourceImageItem.Name)}_滤镜#{cc.ToArgb().ToString("X")}{Path.GetExtension(sourceImageItem.Name)}");
            imageItems.Add(ii);
            if (objectBrowser != null)
            {
                objectBrowser.UpdateObject();
                objectBrowser.ToClickItemLink(ii);
            }
            else
            {
                imageItemClick(ii);
            }
            splashScreenManager.CloseWaitForm();
        }
        #endregion

        #region 打开文件
        private void barButtonItemOpen_ItemClick(object sender, ItemClickEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.FileName = @"F:\@Personal\Photo\壁纸\backiee";
            fileDialog.Title = "选择图片";
            fileDialog.Filter = "位图文件(*.jpg,*.jpeg,*.png)|*.jpg;*.jpeg;*.png";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                Image image = Image.FromFile(fileDialog.FileName);
                ImageItem ii = new ImageItem(image, Path.GetFileName(fileDialog.FileName));
                imageItems.Add(ii);
                if (objectBrowser != null)
                {
                    objectBrowser.UpdateObject();
                    objectBrowser.ToClickItemLink(ii);
                }
                else
                {
                    imageItemClick(ii);
                }
            }
        }
        #endregion

        #region 保存
        private void barButtonItemSave_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (!(currentDocForm is FrmImg))
            {
                return;
            }
            ImageItem imageItem = ((FrmImg)currentDocForm).ImageItem;
            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Title = "保存图片";
                saveFileDialog.FileName = imageItem.Name;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.Filter = "位图文件(*.jpg)|*.jpg|位图文件(*.jpeg)|*.jpeg|透明位图文件(*.png)|*.png";
                saveFileDialog.FilterIndex = 0;
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    imageItem.Image.Save(saveFileDialog.FileName);
                }
            }
        }
        #endregion

        #region 复制图像
        private void barButtonItemCopyImg_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (currentDocForm is FrmImg)
            {
                Image img = ((FrmImg)currentDocForm).ImageItem.Image;
                Clipboard.SetImage(img);
            }
        }
        #endregion

        #region 重命名对象
        private void barButtonItemRename_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (!(currentDocForm is FrmImg || currentDocForm is FrmClasses))
            {
                return;
            }
            XtraForm xf = currentDocForm;
            if (xf is FrmImg)
            {
                string nname = XtraInputBox.Show("请输入新名称", "重命名", Path.GetFileNameWithoutExtension(xf.Text)).Trim();
                if (!string.IsNullOrEmpty(nname))
                {
                    xf.Text = nname + Path.GetExtension(xf.Text);
                    ((FrmImg)xf).ImageItem.Name = xf.Text;
                }
            }
            else if (xf is FrmClasses)
            {
                string nname = XtraInputBox.Show("请输入新名称", "重命名", xf.Text).Trim();
                if (!string.IsNullOrEmpty(nname))
                {
                    xf.Text = nname;
                    ((FrmClasses)xf).ClusteringItem.Name = nname;
                }
            }
            objectBrowser.UpdateObject();
        }
        #endregion

        #region 销毁对象
        private void barButtonItemDel_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (currentDocForm == null)
            {
                return;
            }
            if (XtraMessageBox.Show($"确定要销毁[{currentDocForm.Text}]吗？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
            {
                return;
            }
            if (currentDocForm is FrmImg)
            {
                imageItems.Remove(((FrmImg)currentDocForm).ImageItem);
            }
            else if (currentDocForm is FrmClasses)
            {
                clusteringItems.Remove(((FrmClasses)currentDocForm).ClusteringItem);
            }
            currentDocForm.Close();
            objectBrowser.UpdateObject();
        }
        #endregion

        #region 提取主色
        private void barButtonItemStartClasses_ItemClick(object sender, ItemClickEventArgs e)
        {
            splashScreenManager.ShowWaitForm();
            if (!(currentDocForm is FrmImg))
            {
                return;
            }
            ClusteringItem ci = new ClusteringItem(((FrmImg)currentDocForm).ImageItem, Convert.ToInt32(barEditItemClassCount.EditValue.ToString()), Convert.ToInt32(barEditItemLimit.EditValue.ToString()), Convert.ToInt32(barEditItemSkip.EditValue.ToString()));
            ci.Start(p =>
            {
                splashScreenManager.SetWaitFormDescription($"正在提取主色, 已完成 {p}%");
            });
            clusteringItems.Add(ci);
            if (objectBrowser != null)
            {
                objectBrowser.UpdateObject();
                objectBrowser.ToClickItemLink(ci);
            }
            else
            {
                clusteringItemClick(ci);
            }
            popupMenuClasses.ItemLinks.Clear();
            popupMenuClasses.AddItems(clusteringItems.Select(c =>
            {
                var btn = new BarButtonItem();
                btn.Caption = c.Name;
                btn.ImageOptions.Image = c.PreviewBitmap;
                btn.ItemClick += (s, arg) =>
                {
                    Dictionary<Color, Color> ccc = new Dictionary<Color, Color>();
                    foreach (var cc in c.ColorClustering.ColorClasses)
                    {
                        ccc.Add(cc.Center, cc.Center);
                    }
                    Coloring(ccc);
                };
                return btn;
            }).ToArray());
            popupMenuCustom.ItemLinks.Clear();
            popupMenuCustom.AddItems(clusteringItems.Select(c =>
            {
                var btn = new BarButtonItem();
                btn.Caption = c.Name;
                btn.ImageOptions.Image = c.PreviewBitmap;
                btn.ItemClick += (s, arg) =>
                {
                    Dictionary<Color, Color> ccc = new Dictionary<Color, Color>();
                    foreach (var cc in c.ColorClustering.ColorClasses)
                    {
                        if (ccc.ContainsKey(cc.Center)) continue;
                        ccc.Add(cc.Center, cc.Center);
                    }
                    ShowShadingOptions(ccc);
                };
                return btn;
            }).ToArray());
            splashScreenManager.CloseWaitForm();
        }
        #endregion

        #region 灰度处理
        private void barButtonItemGray_ItemClick(object sender, ItemClickEventArgs e)
        {
            splashScreenManager.ShowWaitForm();
            splashScreenManager.SetWaitFormDescription("正在灰度化");
            if (!(currentDocForm is FrmImg))
            {
                return;
            }
            ImageItem sourceImageItem = ((FrmImg)currentDocForm).ImageItem;
            Image image = new ImageHelper((Bitmap)sourceImageItem.Image).GetGray();
            ImageItem ii = new ImageItem(image, $"{Path.GetFileNameWithoutExtension(sourceImageItem.Name)}_灰度{Path.GetExtension(sourceImageItem.Name)}");
            imageItems.Add(ii);
            if (objectBrowser != null)
            {
                objectBrowser.UpdateObject();
                objectBrowser.ToClickItemLink(ii);
            }
            else
            {
                imageItemClick(ii);
            }
            splashScreenManager.CloseWaitForm();
        }
        #endregion

        #region 反色处理
        private void barButtonItemAnti_ItemClick(object sender, ItemClickEventArgs e)
        {
            splashScreenManager.ShowWaitForm();
            splashScreenManager.SetWaitFormDescription("正在反色处理");
            if (!(currentDocForm is FrmImg))
            {
                return;
            }
            ImageItem sourceImageItem = ((FrmImg)currentDocForm).ImageItem;
            Image image = new ImageHelper((Bitmap)sourceImageItem.Image).GetAnti();
            ImageItem ii = new ImageItem(image, $"{Path.GetFileNameWithoutExtension(sourceImageItem.Name)}_反色{Path.GetExtension(sourceImageItem.Name)}");
            imageItems.Add(ii);
            if (objectBrowser != null)
            {
                objectBrowser.UpdateObject();
                objectBrowser.ToClickItemLink(ii);
            }
            else
            {
                imageItemClick(ii);
            }
            splashScreenManager.ShowWaitForm();
        }
        #endregion

        #region 二值处理
        private void barButtonItemVal2_ItemClick(object sender, ItemClickEventArgs e)
        {
            splashScreenManager.ShowWaitForm();
            if (!(currentDocForm is FrmImg))
            {
                return;
            }
            ImageItem sourceImageItem = ((FrmImg)currentDocForm).ImageItem;
            Image image = new ImageHelper((Bitmap)sourceImageItem.Image).GetVal2(p =>
            {
                splashScreenManager.SetWaitFormDescription($"正在二值化，已完成{p}%");
            });
            ImageItem ii = new ImageItem(image, $"{Path.GetFileNameWithoutExtension(sourceImageItem.Name)}_二值{Path.GetExtension(sourceImageItem.Name)}");
            imageItems.Add(ii);
            if (objectBrowser != null)
            {
                objectBrowser.UpdateObject();
                objectBrowser.ToClickItemLink(ii);
            }
            else
            {
                imageItemClick(ii);
            }
            splashScreenManager.CloseWaitForm();
        }


        #endregion

        private void Transforming(TransformType transformType)
        {
            splashScreenManager.ShowWaitForm();
            if (!(currentDocForm is FrmImg))
            {
                return;
            }
            ImageItem sourceImageItem = ((FrmImg)currentDocForm).ImageItem;
            Image image = new ImageHelper((Bitmap)sourceImageItem.Image).GetTransform(transformType, p =>
            {
                splashScreenManager.SetWaitFormDescription($"正在变换，已完成{p}%");
            });
            ImageItem ii = new ImageItem(image, $"{Path.GetFileNameWithoutExtension(sourceImageItem.Name)}_变换{Path.GetExtension(sourceImageItem.Name)}");
            imageItems.Add(ii);
            if (objectBrowser != null)
            {
                objectBrowser.UpdateObject();
                objectBrowser.ToClickItemLink(ii);
            }
            else
            {
                imageItemClick(ii);
            }
            splashScreenManager.CloseWaitForm();
        }

        private void Resizeing(ResizeSettings settings)
        {
            splashScreenManager.ShowWaitForm();
            if (!(currentDocForm is FrmImg))
            {
                return;
            }
            ImageItem sourceImageItem = ((FrmImg)currentDocForm).ImageItem;
            int width = settings.SWidth;
            int height = settings.SHeight;
            if (settings.Percent)
            {
                width = sourceImageItem.Image.Width * width / 100;
                height = sourceImageItem.Image.Height * height / 100;
            }
            Image image = new ImageHelper((Bitmap)sourceImageItem.Image).GetTransformResize(new Size(width, height), settings.ResizeMode);
            ImageItem ii = new ImageItem(image, $"{Path.GetFileNameWithoutExtension(sourceImageItem.Name)}_{width}×{height}{Path.GetExtension(sourceImageItem.Name)}");
            imageItems.Add(ii);
            if (objectBrowser != null)
            {
                objectBrowser.UpdateObject();
                objectBrowser.ToClickItemLink(ii);
            }
            else
            {
                imageItemClick(ii);
            }
            splashScreenManager.CloseWaitForm();
        }

        private void barButtonItemRotationShun_ItemClick(object sender, ItemClickEventArgs e)
        {
            Transforming(TransformType.Shun);
        }

        private void barButtonItemRotationNi_ItemClick(object sender, ItemClickEventArgs e)
        {
            Transforming(TransformType.Ni);
        }

        private void barButtonItemTLR_ItemClick(object sender, ItemClickEventArgs e)
        {
            Transforming(TransformType.LR);
        }

        private void barButtonItemTUD_ItemClick(object sender, ItemClickEventArgs e)
        {
            Transforming(TransformType.UD);
        }

        private void barButtonItemTC_ItemClick(object sender, ItemClickEventArgs e)
        {
            Transforming(TransformType.Center);
        }

        private void barButtonItemResize_ItemClick(object sender, ItemClickEventArgs e)
        {
            ShowResizeSettings();
        }

        private void barButtonItemColoring_ItemClick(object sender, ItemClickEventArgs e)
        {
            if(dockPanelShadingOptions != null)
            {
                dockPanelShadingOptions.Focus();
                return;
            }

            if (clusteringItems.Count > 0)
            {
                Dictionary<Color, Color> ccc = new Dictionary<Color, Color>();
                foreach (var cc in clusteringItems[0].ColorClustering.ColorClasses)
                {
                    if (ccc.ContainsKey(cc.Center)) continue;
                    ccc.Add(cc.Center, cc.Center);
                }
                ShowShadingOptions(ccc);
            }
        }
    }
}